﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Macds.Core.Web
{
    public abstract class WebRequestBase
    {
        /// <summary>
        /// By default is false
        /// </summary>
        public bool IsAsync { get; set; }

        /// <summary>
        /// Open a connection to any URL provided and send the parameters using POST by default
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns>string of the response back from the URL called</returns>
        public virtual string SendRequest(string url, string postData)
        {
            return SendRequest(url, postData, RequestMethod.POST, "", "", new Dictionary<string,string>());
        }

        /// <summary>
        /// Open a connection to any URL provided and send the parameters using the request method of your choice
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="method"></param>
        /// <returns>string of the response back from the URL called</returns>
        public virtual string SendRequest(string url, string postData, RequestMethod method)
        {
            return SendRequest(url, postData, method, "", "", new Dictionary<string,string>());
        }

        /// <summary>
        /// Open a connection to any URL provided and send the parameters using the request method of your choice
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="method"></param>
        /// <param name="returnContentType"></param>
        /// <returns>string of the response back from the URL called</returns>
        public virtual string SendRequest(string url, string postData, RequestMethod method, string returnContentType)
        {
            return SendRequest(url, postData, method, "", returnContentType, new Dictionary<string,string>());
        }

        /// <summary>
        /// Open a connection to any URL provided and send the parameters using the request method of your choice
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="method"></param>
        /// <param name="returnContentType"></param>
        /// <param name="headers"></param>
        /// <returns>string of the response back from the URL called</returns>
        public virtual string SendRequest(string url, string postData, RequestMethod method, string returnContentType, Dictionary<string, string> headers)
        {
            return SendRequest(url, postData, method, "", returnContentType, headers);
        }

        /// <summary>
        /// Open a connection to any URL provided and send the parameters provided
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="method">POST or GET</param>
        /// <param name="contentType">A string representing the MIME content type of the incoming request, for example, "text/html"</param>
        /// <returns></returns>
        public virtual string SendRequest(string url, string postData, RequestMethod method, string contentType, string returnContentType, Dictionary<string, string > headers)
        {
            string responseInfo = string.Empty;

            if (method == RequestMethod.GET)
                url = postData == "" ? url : url + "?" + postData;

            UTF8Encoding enconding = new UTF8Encoding();
            byte[] data = enconding.GetBytes(postData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = method.ToString();

            if (headers.Count > 0)
            {
                foreach (var header in headers)
                {
                    var headerType = (HttpRequestHeader)Enum.Parse(typeof(HttpRequestHeader), header.Key);
                    request.Headers.Add(headerType, header.Value);
                }
            }

            if (!String.IsNullOrEmpty(returnContentType))
                request.Accept = returnContentType;

            if (method == RequestMethod.POST)
            {
                request.ContentLength = data.Length;
                request.ContentType = contentType;

                if(string.IsNullOrEmpty(contentType))
                    request.ContentType = "application/x-www-form-urlencoded";

                using (Stream outStream = request.GetRequestStream())
                {
                    outStream.Write(data, 0, data.Length);
                    outStream.Close();
                }
            }

            using (HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(webresponse.GetResponseStream(), enconding))
                {
                    responseInfo = reader.ReadToEnd();
                    if (responseInfo.IndexOf("\r\n") != -1)
                        responseInfo = responseInfo.Replace("\r\n", "");
                    reader.Close();
                }

                webresponse.Close();
            }

            return responseInfo;
        }
    }
}
